import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import io.jboot.web.controller.JbootControllerContext;
import io.jboot.web.directive.annotation.JFinalDirective;
import io.jboot.web.directive.base.JbootDirectiveBase;
import io.jboot.web.directive.base.PaginateDirectiveBase;
import io.jpress.JPressOptions;
import io.jpress.commons.directive.DirectveKit;
import io.jpress.module.article.model.Article;
import io.jpress.module.article.model.ArticleCategory;

import javax.servlet.http.HttpServletRequest;

@JFinalDirective("ArticleEnhancePage")
public class ArticlePageDirective extends JbootDirectiveBase {

    @Inject
    private ArticleEnhanceService service;

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        Controller controller = JbootControllerContext.get();
        Integer page = getPara("page",scope);
        if(page == null) {
            page = controller.getParaToInt(1, 1);
        }
        int pageSize = getParaToInt("pageSize", scope, 10);
        String orderBy = getPara("orderBy", scope, "id desc");
//        String where = getPara("where", scope);
        String keyword = controller.getPara("keyword");

        // 可以指定当前的分类ID
        Long categoryId = getParaToLong("categoryId", scope, 0L);
        Integer tagid = getParaToInt("tagid", scope);
        ArticleCategory category = controller.getAttr("category");

        if (categoryId == 0 && category != null) {
            categoryId = category.getId();
        }
        Page<Article> articlePage;
        if(categoryId == 0 && keyword == null && tagid == null){
            articlePage = service.paginateInNormal(page, pageSize, orderBy);
        }else if(categoryId >0 && tagid == null){
            SqlPara sqlPara = new SqlPara();
            sqlPara.setSql(
                    "select * from article p,article_category_mapping acm where acm.category_id = ? and acm.article_id = p.id"
            );
            sqlPara.addPara(categoryId);
            articlePage = service.paginate(page, pageSize, sqlPara);
        }else if(keyword != null && categoryId!=null && tagid != null){
            String sql = " title like ?";
            articlePage = service.paginateByCategoryIdInNormal(page, pageSize, categoryId,tagid,sql,"%"+keyword+"%");;
        }else{
            articlePage = service.paginateByCategoryIdInNormal(page, pageSize, categoryId,tagid);
        }

        scope.setGlobal("ArticleEnhancePage", articlePage);
        renderBody(env, scope, writer);
    }

    @Override
    public boolean hasEnd() {
        return true;
    }


    @JFinalDirective("ArticleEnhancePaginate")
    public static class TemplatePaginateDirective extends PaginateDirectiveBase {

        @Override
        protected String getUrl(int pageNumber, Env env, Scope scope, Writer writer) {
            HttpServletRequest request = JbootControllerContext.get().getRequest();
            String url = request.getRequestURI();
            String contextPath = JFinal.me().getContextPath();

            boolean firstGotoIndex = getPara("firstGotoIndex", scope, false);

            if (pageNumber == 1 && firstGotoIndex) {
                return contextPath + "/";
            }

            // 如果当前页面是首页的话
            // 需要改变url的值，因为 上一页或下一页是通过当前的url解析出来的
            if (url.equals(contextPath + "/")) {
                url = contextPath + "/article/category/index"
                        + JPressOptions.getAppUrlSuffix();
            }
            return DirectveKit.replacePageNumber(url, pageNumber);
        }

        @Override
        protected Page<?> getPage(Env env, Scope scope, Writer writer) {
            return (Page<?>) scope.get("ArticleEnhancePage");
        }

    }
}
